/*
 * @Author: intellectual-seeker 3336339701@qq.com
 * @Date: 2025-11-18 12:55:32
 * @LastEditors: intellectual-seeker 3336339701@qq.com
 * @LastEditTime: 2025-11-18 15:31:13
 * @FilePath: /code/lesson34/test1/UdpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include "InetAddr.hpp"
#include "Log.hpp"
#include <cstring>
#include <cstdlib>
#include <strings.h>

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    USAGE_ERROR
};

static int defualt_fd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port)
        :_sockfd(defualt_fd), _port(port)
    {}

    void InitServer()
    {
        //1. 创建socket fd
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket error: %s, %d", strerror(errno), errno);
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success");

        //2. 填充struct sockaddr_in
        struct sockaddr_in local;
        bzero(&local, sizeof(sockaddr_in));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        //3. 绑定
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error: %s %d", strerror(errno), errno);
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success");
    }

    void Start()
    {
        //先收后发
        _isrunning = true;

        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            char buf[1024];

            ssize_t n = recvfrom(_sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                buf[n] = 0;
                InetAddr addr(peer);
                LOG(INFO, "get message from [%s:%d]: %s", addr.Ip().c_str(), addr.Port(), buf);
                sendto(_sockfd, buf, strlen(buf), 0, (struct sockaddr*)&peer, len);
            }
        }

        _isrunning = false;
    }

    ~UdpServer()
    {}

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
};